--
-- Author: shunguo.chen
-- Date: 2018-02-06 11:02:29
--
-- WorldMapView 世界地图界面

local MapIconRender = import(".renders.MapIconRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.WorldMapScene

local YEAR_STR = L("lua_code_text_533")

function ClassRef:init()
	local bc = app:getInst("BiddingController")
	bc:reqTownList()

	self._ui.Button_close:addClickEventListener(function()
			executeFunc(self._onCloseView)
		end)
	self._ui.selected_btn_map:addClickEventListener(function()
			-- self:switchPanel(1)
		end)
	self._ui.selected_btn_battle:addClickEventListener(function()
			if bc.battleMapModel then
				if bc.battleMapModel.townInfos[1].data.phase == "CLOSE" then
					display.pushToast(L"bidding_tips_not_open")
				else
					app:sendMsg("WorldMapController", "closeView" )
					app:sendMsg("WorldBattleController", "openView" )
				end
			end	
		end)
	self._ui.selected_btn_map:setBright(false)
	-- display.setBtnTouchEnable(self._ui.selected_btn_battle, false)

	self._yearText = self._ui["Panel/Panel_tlt/time"]

	self._renders = {0,0,0,0,0}
	local mapPanel = self._ui.Panel_map
	for i=1,10 do
		local node = mapPanel:getChildByName("Panel_" .. i)
		if node then
			local render = MapIconRender.create(node)
			render:onBtnClick(handler(self, self._onClickRender))
			self._renders[i] = render
		else
			break
		end
	end

	self._renderHeight = self._renders[1]:getContentSize().height
end

function ClassRef:show()
	self.super.show(self)
end

-- index 1	map
-- index 2	battle
function ClassRef:switchPanel(index)
	if self._idx == index then return end
	self._idx = index


end

function ClassRef:_onClickRender(render)
	local data = render:getData()
	if data:isOpen() then
		executeFunc(self._onOperate, "openMap", data.id)
	else
		display.pushToast(L("lua_code_text_458"))
	end
end

-- 设置船的位置
function ClassRef:_refreshShip(render)
	if not self._ship then
		self._ship = cc.CSLoader:createNode(Res.WorldMapShipNode)
		self._ship:getTimeline():gotoFrameAndPlay(0, true)
		self._ui.Panel_map:addChild(self._ship)

		local panel = self._ship:findChild("Panel/button")
		panel:addClickEventListener(function()
				executeFunc(self._onOperate, "goHome")
			end)
	end

	self._ship:setPositionX(render:getPositionX())
	self._ship:setPositionY(render:getPositionY() + self._renderHeight / 2)
end

-- mapInfos = {MapInfo, MapInfo, ...}
function ClassRef:refresh(mapInfos)
	local gameDate = app.session:getVirtualTime()
	self._yearText:setString(string.format(YEAR_STR, gameDate.year))

	for i,render in ipairs(self._renders) do
		local data = mapInfos[i]
		render:setVisible(data ~= nil)
		if data then
			render:setData(data)
			local isCurMap = data:isCurMap()
			-- render:setClickEnable(not isCurMap)
			if isCurMap then
				self:_refreshShip(render)
			end
		end
	end
end

return ClassRef